package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import cn.com.kh.KHUtil;
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.getProperty;


/**
 *
 * @Title: 华盛证券备注接口对接
 * @Description: 查询备注信息列表及添加备注信息
 * @author: tian
 * @date 2021-07-07 17:42:00
 *
 */

public class apiHSTNotes implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiHSTNotes.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";
        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }
        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {
            long startTime = System.currentTimeMillis();
            long endTime = 0;
            String reJson = null;

            // 调用处理信息
            JSONObject inObject = new JSONObject(inData);
            //公共变量
            def token = GetJV(inObject, "token");//token
            def operate_type = GetJV(inObject, "operate_type");//1查询备注信息列表2添加备注信息
            def hsNo = GetJV(inObject, "hsNo");//华盛号

            String dealMessage="";
            HashMap<String, String> paramHashMap = new HashMap<String, String>()
            String sign_time=Instant.now().getEpochSecond();
            log.debug("解析信息-时间戳" +  "sign_time: " + sign_time);
            if(operate_type=="1"){
                //查询备注信息列表
                def status = GetJV(inObject, "status");//状态(0表示未删除1表示删除)
                def equalCommentAtType = GetJV(inObject, "equalCommentAtType");//（10服顾添加11客服添加）
                log.debug("备注查询接口："+ "token: " + token+ "|hsNo: " + hsNo+ "|status: " + status+ "|equalCommentAtType: " + equalCommentAtType);
                //必填校验
                dealMessage = KHUtil.isNullMSG("hsNo", hsNo);
                if (!KHUtil.isNull(dealMessage)) {
                    outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + dealMessage + ")\",\"data\":[]}";
                    return outData;
                }
                paramHashMap.put("sign_time", sign_time);//时间戳
                paramHashMap.put("token", token);//页面传入token
                paramHashMap.put("hsNo", hsNo);//查询条件-华盛号
                paramHashMap.put("status", status);//查询条件-状态
                paramHashMap.put("equalCommentAtType", equalCommentAtType);//查询条件-添加来源
                String queryComment = getProperty.get("HSTURL")+"/crm/member/queryComment"; //查询备注接口地址
                String injson=getSign(paramHashMap);
                outData = Querypromocode(eliteBean, injson,dataSourceID,queryComment);
            }else if(operate_type=="2"){
                //新增备注信息
                def type = GetJV(inObject, "type");//添加来源(服顾添加10，客服添加11)
                def comment = GetJV(inObject, "comment");//备注内容
                def operator = GetJV(inObject, "operator");//操作人工号
                log.debug("备注新增接口："+ "token: " + token+ "|hsNo: " + hsNo+ "|type: " + type+ "|comment: " + comment+ "|operator: " + operator);
                //必填校验
                dealMessage = KHUtil.isNullMSG("hsNo", hsNo)+KHUtil.isNullMSG("type", type)+KHUtil.isNullMSG("comment", comment)+KHUtil.isNullMSG("operator", operator);
                if (!KHUtil.isNull(dealMessage)) {
                    outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + dealMessage + ")\",\"data\":[]}";
                    return outData;
                }
                paramHashMap.put("sign_time", sign_time);//时间戳
                paramHashMap.put("token", token);//页面传入token
                paramHashMap.put("hsNo", hsNo);//新增内容-华盛号
                paramHashMap.put("type", type);//新增内容-添加来源
                paramHashMap.put("comment", comment);//新增内容-备注
                paramHashMap.put("operator", operator);//新增内容-操作人工号
                String submitComment = getProperty.get("HSTURL")+"/crm/member/submitComment"; //添加备注接口地址
                String injson=getSign(paramHashMap);
                outData = Querypromocode(eliteBean, injson,dataSourceID,submitComment);
            }else{
                outData = "{\"result\":\"-1\",\"message\":\"处理失败(无法识别的操作类型：" + operate_type + ")\",\"data\":[]}";
                return outData;
            }
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }
        log.debug("处理完成返回结果:" + outData);
        return outData;
    }

    //获取加密签名及拼接请求参数
    public String getSign(HashMap<String, String> paramHashMap){
        //鉴权变量
        String appid = getProperty.get("appid");
        String appsecret = getProperty.get("appsecret");
        //sign加密前后
        String signfront = "";
        String signafter = "";
        log.debug("paramHashMap：" + paramHashMap);
        //自然排序 升序参数
        signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
        log.debug("sign加密MD5前：" + signfront);
        signafter = Util.getMD5Str(signfront);
        log.debug("sign加密MD5后：" + signafter);
        //拼接接口入参
        paramHashMap.put("client_key", appid);
        paramHashMap.put("sign", signafter);

        String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
        log.debug("injson:" + injson);
        return injson;
    }

    //调用查询接口查询备注信息列表||调用接口添加备注信息
    public static String Querypromocode(EliteBean eliteBean,String injson, String dataSourceID,String doURL) {
        String reJson = null;
        try {
            log.debug("doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("返回的参数getResult:" + getResult);

            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "code");
            String result = GetJV(jsonObject, "result");

            JSONObject dataObject;
            log.debug("code:" + code);
            if(code == "00000") {

                reJson = "{\"result\":\"1\",\"message\":"+ result +"}";

            }else {
				String msg = GetJV(jsonObject, "msg")+"|"+GetJV(jsonObject, "error");
				reJson = "{\"result\":\"-1\",\"message\":\"接口调度失败(" + msg + ")\"}";
			}

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"result\":\"-1\",\"message\":\"接口异常\"}";
        }
        return reJson;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
